package com.dog.threesixty;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dog.utils.Constants;
import com.dog.utils.DownloadCompletionListener;
import com.dog.utils.DownloadingItem;
import com.dog.utils.NoRepeatRandom;
import com.dog.utils.Utils;
import com.dog.utils.Downloader;
import com.inapp.util.Base64;
import com.inapp.util.BillingService;
import com.inapp.util.CPurchaseObserver;
import com.inapp.util.Consts;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class HomeScreenActivity extends Activity implements OnClickListener {

	private ImageView imageView;

	private Random random = new Random();
	private NoRepeatRandom nrr;
	private int imageIndex = -1;

	private int imagesToShow[] = { R.drawable.dog0_2x,R.drawable.dog1_2x, R.drawable.dog2_2x,
			R.drawable.dog3_2x, R.drawable.dog4_2x, R.drawable.dog5_2x,
			R.drawable.dog6_2x, R.drawable.dog7_2x, R.drawable.dog8_2x,
			R.drawable.dog9_2x, R.drawable.dog10_2x, R.drawable.dog11_2x,
			R.drawable.dog12_2x, R.drawable.dog13_2x, R.drawable.dog14_2x };

	private boolean isExit;

	private ImageView learnView;
	private ImageView recallView;
	private ImageView vettalkView;

	private JSONObject jo;
	private String fileNames[];

	private boolean isPack1Downloaded;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_home_screen);

		try {
			sharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(this);
			sharedPreferences.registerOnSharedPreferenceChangeListener(ospcl);
			mHandler = new Handler();

			BillingService.register(new CPurchaseObserver(this, mHandler));
			mBillingService = new BillingService();
			mBillingService.setContext(this);
			mBillingService.restoreInAppTransactions();
		} catch (Exception e) {
			e.printStackTrace();
		}

		imageView = (ImageView) findViewById(R.id.imageView);

		learnView = (ImageView) findViewById(R.id.learnView);
		learnView.setOnClickListener(this);

		recallView = (ImageView) findViewById(R.id.recallView);
		recallView.setOnClickListener(this);

		vettalkView = (ImageView) findViewById(R.id.vettalkView);
		vettalkView.setOnClickListener(this);

		showImageInPeriod();

	}

	@Override
	protected void onDestroy() {
		try {
			if (sharedPreferences != null && ospcl != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(ospcl);
			}
			mBillingService.unbind();
			BillingService.unregister();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			isExit = true;
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showImageInPeriod() {
		try {
			new AsyncTask<String, String, String>() {
				private boolean isInvisible;

				@Override
				protected void onPreExecute() {
					try {

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {
					imageView.setBackgroundResource(imagesToShow[imageIndex]);

				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						while (!isExit) {
							if (imageIndex < (imagesToShow.length - 1)) {
								imageIndex++;
							} else {
								imageIndex = 0;
							}
							publishProgress("");
							Thread.sleep(4000);

						}

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		isPack1Downloaded = Utils.isImageDownloaded(HomeScreenActivity.this,
				Constants.IS_PACK_DOWNLOADED + "1");
		switch (v.getId()) {
		case R.id.learnView:
			if (isPack1Downloaded) {
				isExit = true;
				Intent intent = new Intent(HomeScreenActivity.this,
						LearningBeforeActivity.class);
				intent.putExtra(Constants.KEY_QUIZ, Constants.QUIZ_LEARNING);
				startActivity(intent);
			} else {
				showDownloadPopUp();
			}
			break;
		case R.id.recallView:
			if (isPack1Downloaded) {
				isExit = true;
				Intent in = new Intent(HomeScreenActivity.this,
						RecallBeforeActivity.class);
				in.putExtra(Constants.KEY_QUIZ, Constants.QUIZ_RECALL);
				startActivity(in);
			} else {
				showDownloadPopUp();
			}
			break;

		case R.id.vettalkView:
			if (isPack1Downloaded) {
				// isExit = true;
				// Intent i = new Intent(HomeScreenActivity.this,
				// VettalkActivity.class);
				// startActivity(i);
				startVettalk();
			} else {
				showDownloadPopUp();
			}
			// showVettalkScreen();
			break;

		default:
			break;
		}

	}

	// ////////////////////////////INAPP_PURCHASE_RELATED//////////////////////////////////////

	private static final String KEY_PURCHASE_COMMAND = "COMMAND_PURCHASE";
	private static final String KEY_TIME = "t";
	private static final String KEY_ITEM_ID = "i";
	private Handler mHandler;

	private BillingService mBillingService;

	private SharedPreferences sharedPreferences;
	private final OnSharedPreferenceChangeListener ospcl = new OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(final SharedPreferences sp,
				String key) {
			try {
				if (KEY_PURCHASE_COMMAND.equals(key)) {
					runOnUiThread(new Runnable() {
						public void run() {
							try {
								String object = sp.getString(
										KEY_PURCHASE_COMMAND, null);
								if (object != null) {
									JSONObject jo = new JSONObject(object);
									String itemId = jo.getString(KEY_ITEM_ID);

									// Test inapp purchase start
									// Log.i("DREG", "ITEM_ID=" + itemId);
									// sharedPreferences
									// .edit()
									// .putBoolean(
									// Base64.encode(itemId
									// .getBytes()), true)
									// .commit();
									// sharedPreferences
									// .edit()
									// .putLong(
									// BillingService.KEY_IN_APP_PURCHASED_ITEM_CHANGED_TIME,
									// System.currentTimeMillis())
									// .commit();
									//
									// Toast.makeText(
									// HomeScreenActivity.this,
									// "PURCHASE="
									// + BillingService
									// .isPurchased(
									// sharedPreferences,
									// itemId),
									// Toast.LENGTH_LONG).show();
									//
									// Log.i("DREG",
									// "PURCHASE ="
									// + BillingService
									// .isPurchased(
									// sharedPreferences,
									// itemId));

									// Test inapp purchase end

									if (mBillingService.requestPurchase(itemId,
											Consts.ITEM_TYPE_INAPP, null)) {

										Toast.makeText(HomeScreenActivity.this,
												"Requesting to Google play",
												Toast.LENGTH_LONG).show();
									} else {
										Utils.showAlertMessage(
												HomeScreenActivity.this, null,
												"PURCHASING NOT SUPPORTED , CHANGE MESSAGE");
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	public static void requestPurchase(SharedPreferences sp, String itemId) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_ITEM_ID, itemId);
			sp.edit().putString(KEY_PURCHASE_COMMAND, jo.toString()).commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void downloadImage() {
		try {
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;
				private int imageIndex = 0;
				private JSONObject jo;
				private JSONArray ja;

				@Override
				protected void onPreExecute() {
					try {

						jo = new JSONObject(new String(Utils.getFileData(
								HomeScreenActivity.this,
								Constants.PACK1_JSON_FILE)));
						ja = jo.getJSONObject("root").getJSONArray("dog");
						progressDialog = new ProgressDialog(
								HomeScreenActivity.this);
						progressDialog.setMessage("Downloading....");
						progressDialog.setIndeterminate(false);
						progressDialog.setCancelable(false);
						progressDialog.setMax(ja.length());
						progressDialog
								.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

						progressDialog.show();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {
					try {
						progressDialog.setProgress(imageIndex);
						if (imageIndex == ja.length()) {
							Toast.makeText(HomeScreenActivity.this,
									"Download completed", Toast.LENGTH_SHORT)
									.show();
							Utils.setImageDownloaded(HomeScreenActivity.this,
									Constants.IS_PACK_DOWNLOADED + "1", true);

						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						while (imageIndex < ja.length()) {

							String fileName = ja.getJSONObject(imageIndex)
									.getString("-part");
							String url = Constants.PACK1_STANDARD_URL
									+ Utils.getAndroidFormattedUrl(fileName)
									+ ".png";
							fileName = fileName + ".png";
							Log.i("DREG", "File Name=" + fileName);
							Log.i("DREG", "Url =" + url);
							Downloader.downloadFile(Constants.PACK1_DIRECTORY,
									fileName, url, HomeScreenActivity.this);
							imageIndex++;
							publishProgress("");
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {
					progressDialog.dismiss();

				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showDownloadPopUp() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(
				HomeScreenActivity.this);
		builder.setMessage(
				"You have to download 67 HD images(at about 4 MB).Do you want to download ?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
								if (Utils
										.isDeviceOnline(HomeScreenActivity.this)) {
									downloadImage();
								} else {
									Utils.showAlertMessage(
											HomeScreenActivity.this,
											android.R.drawable.ic_dialog_alert,
											"Connection Error",
											"Please check your internet connection");
								}
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		final AlertDialog alert = builder.create();
		alert.setTitle("Oops !");
		alert.show();
	}

	private void showVettalkScreen() {
		try {
			isPack1Downloaded = Utils
					.isImageDownloaded(HomeScreenActivity.this,
							Constants.IS_PACK_DOWNLOADED + "1");
			boolean mainBundlePurchased = BillingService.isPurchased(
					sharedPreferences, Constants.BUNDLE_ITEM_ID);
			boolean pak2Purchased = BillingService.isPurchased(
					sharedPreferences, Constants.PACK2_ITEM_ID);
			boolean pack3Purchased = BillingService.isPurchased(
					sharedPreferences, Constants.PACK3_ITEM_ID);
			boolean pack4Purchased = BillingService.isPurchased(
					sharedPreferences, Constants.PACK4_ITEM_ID);
			boolean pack5Purchased = BillingService.isPurchased(
					sharedPreferences, Constants.PACK5_ITEM_ID);

			List<DownloadingItem> downloadingItems = new ArrayList<DownloadingItem>();

			if (!Utils.containsAllFiles(Constants.PACK1_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(HomeScreenActivity.this,
							Constants.PACK1_JSON_FILE)))) {
				DownloadingItem di = new DownloadingItem();
				di.setBASE_URL(Constants.PACK1_STANDARD_URL);
				di.setIMAGE_DIRECTORY(Constants.PACK1_DIRECTORY);
				di.setImageFileName(Utils.getImageFileName(
						HomeScreenActivity.this, Constants.PACK1_JSON_FILE));
				downloadingItems.add(di);
			}

			if (mainBundlePurchased || pak2Purchased) {
				if (!Utils.containsAllFiles(Constants.PACK2_DIRECTORY, Arrays
						.asList(Utils.getImageFileName(HomeScreenActivity.this,
								Constants.PACK2_JSON_FILE)))) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK2_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK2_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							HomeScreenActivity.this, Constants.PACK2_JSON_FILE));
					downloadingItems.add(di);
				}
			}
			if (mainBundlePurchased || pack3Purchased) {
				if (!Utils.containsAllFiles(Constants.PACK3_DIRECTORY, Arrays
						.asList(Utils.getImageFileName(HomeScreenActivity.this,
								Constants.PACK3_JSON_FILE)))) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK3_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK3_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							HomeScreenActivity.this, Constants.PACK3_JSON_FILE));
					downloadingItems.add(di);
				}
			}
			if (mainBundlePurchased || pack4Purchased) {
				if (!Utils.containsAllFiles(Constants.PACK4_DIRECTORY, Arrays
						.asList(Utils.getImageFileName(HomeScreenActivity.this,
								Constants.PACK4_JSON_FILE)))) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK4_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK4_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							HomeScreenActivity.this, Constants.PACK4_JSON_FILE));
					downloadingItems.add(di);
				}
			}
			if (mainBundlePurchased || pack5Purchased) {
				if (!Utils.containsAllFiles(Constants.PACK5_DIRECTORY, Arrays
						.asList(Utils.getImageFileName(HomeScreenActivity.this,
								Constants.PACK5_JSON_FILE)))) {
					DownloadingItem di = new DownloadingItem();
					di.setBASE_URL(Constants.PACK5_STANDARD_URL);
					di.setIMAGE_DIRECTORY(Constants.PACK5_DIRECTORY);
					di.setImageFileName(Utils.getImageFileName(
							HomeScreenActivity.this, Constants.PACK5_JSON_FILE));
					downloadingItems.add(di);
				}
			}
			if (downloadingItems.size() > 0) {
				if (Utils.isDeviceOnline(HomeScreenActivity.this)) {
					Utils.downloadFiles(HomeScreenActivity.this,
							downloadingItems, new DownloadCompletionListener() {

								@Override
								public void onDownloadError(Exception exception) {
									Utils.showAlertMessage(
											HomeScreenActivity.this, null,
											exception.getMessage());
								}

								@Override
								public void onCompleteDownloading() {
									startVettalk();
								}
							});
				} else {
					Utils.showAlertMessage(HomeScreenActivity.this, null,
							"Please go online to download image files");
				}
			} else {
				startVettalk();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startVettalk() {
		try {
			isExit = true;
			Intent i = new Intent(HomeScreenActivity.this,
					VettalkActivity.class);
			startActivity(i);
		} catch (Exception e) {
			e.fillInStackTrace();
		}
	}

}
